package com.ruoyi.web.controller.exam;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.exam.domain.*;
import com.ruoyi.exam.service.*;
import com.ruoyi.exam.vo.*;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
public class StudentQuestionController extends BaseController {

    @Autowired
    private IPQuestionService ipQuestionService;

    @Autowired
    private IPQuestionBankService pQuestionBankService;

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private IPQuestionRecordService ipQuestionRecordService;

    @Autowired
    private IPWrongQuestionService ipWrongQuestionService;

    @Autowired
    private IPExamRecordLogService ipExamRecordLogService;

    @Autowired
    private IPExamService ipExamService;

    @Autowired
    private IPQuestionEquipmentBankService ipQuestionEquipmentBankService;

    @Autowired
    private IPVideoService pVideoService;

    @Autowired
    private PQuestionTypeService pQuestionTypeService;


    @GetMapping("/getEquipment")
    public AjaxResult getEquipment(){
        List<PQuestionEquipmentBank> pQuestionEquipmentBanks = ipQuestionEquipmentBankService.selectPQuestionEquipmentBankList(new PQuestionEquipmentBank());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("equipment",pQuestionEquipmentBanks);
        return ajax;
    }

    /**
     * 随机考题
     */
    @GetMapping("/findBank")
    public AjaxResult findBank(Long questionEquipmentId) {
        PQuestionBank pQuestionBank = new PQuestionBank();
        List<PQuestionBankVo> pQuestionBankVos = pQuestionBankService.getQuestionBankList(pQuestionBank);
        return  AjaxResult.success(pQuestionBankVos);
    }


    /**
     * 查询题库
     */
    @GetMapping("/findQuestion")
    public TableDataInfo findQuestion(Long bankId, Long questionEquipmentId,Long questionType) {

        StudentQuestionVo studentQuestionVo = new StudentQuestionVo();
        studentQuestionVo.setLevel(questionEquipmentId);
        studentQuestionVo.setQuBankIdOne(bankId);
        studentQuestionVo.setDeleteFlag(0);
        studentQuestionVo.setQuType(questionType);
        studentQuestionVo.setCreateBy(getUserId().toString());
        startPage();
        List<SQuestionResult> sQuestionResults = ipQuestionService.selectSQuestionList(studentQuestionVo);
        return  getDataTable(sQuestionResults);
    }



    /**
     * 查询题目
     */
    @GetMapping("/findQuestionInfo")
    public AjaxResult findQuestionInfo(Long questionId) {
        QuestionVo questionVo = redisCache.getCacheObject("questionId");

        if(questionVo == null){
          questionVo = ipQuestionService.selectPQuestionById(questionId, true);
          return  AjaxResult.success(questionVo);

        }
        return AjaxResult.error("无此题目，请检查后台数据是否完整");

    }

    @PostMapping("/insertQuestionRecord")
    public AjaxResult insertQuestionRecord(@RequestBody PQuestionRecord pQuestionRecord) {
        pQuestionRecord.setCreateBy(getUserId().toString());
        Integer i1 = ipQuestionRecordService.selectPQuestionRecordByCount(pQuestionRecord);
        if(i1.intValue() !=0){
            return AjaxResult.success(i1);
        }else{
            pQuestionRecord.setAnswerStatus(new Long(1));
            int i = ipQuestionRecordService.insertPQuestionRecord(pQuestionRecord);
            return AjaxResult.success(i);
        }

    }


    @PostMapping("/insertExamRecord")
    public AjaxResult insertExamRecord(@RequestBody AddExamRecordVo addExamRecordVo) {

        PExamRecordLog pExamRecordLog = new PExamRecordLog();
        pExamRecordLog.setQuestionIds(addExamRecordVo.getQuestionIds());
        pExamRecordLog.setUserAnswers(addExamRecordVo.getUserAnswer());
        pExamRecordLog.setUserId(getUserId());
        pExamRecordLog.setTotalScore(addExamRecordVo.getTotalScore());//总分
        pExamRecordLog.setErrorQuestionIds(addExamRecordVo.getErrorQuestionIds());
        pExamRecordLog.setLogicScore(addExamRecordVo.getUserScore());//用户得分
        pExamRecordLog.setExamId(addExamRecordVo.getExamId());
        pExamRecordLog.setCreateBy(getUserId().toString());
        pExamRecordLog.setStatus(1);
        int count = ipExamRecordLogService.selectPExamRecordCount(pExamRecordLog);
        if(count > 0){
          ipExamRecordLogService.updatePExamRecordLog(pExamRecordLog);
        }else{
          ipExamRecordLogService.insertPExamRecordLog(pExamRecordLog);
        }


        String[] split = addExamRecordVo.getErrorQuestionIds().split(",");
        String[] split1 = addExamRecordVo.getErrorAnswers().split("-");
        for (int i = 0; i < split.length; i++) {
            PQuestionRecord pQuestionRecord = new PQuestionRecord();
            pQuestionRecord.setQuestionId(Long.valueOf(split[i]));
            pQuestionRecord.setCreateBy(getUserId().toString());
            pQuestionRecord.setAnswerId(split1[i]);
            pQuestionRecord.setStatus(new Long(2));
            pQuestionRecord.setAnswerStatus(new Long(2));
            Integer i1 = ipQuestionRecordService.selectPQuestionRecordByCount(pQuestionRecord);
            if(i1 == 0){
                ipQuestionRecordService.insertPQuestionRecord(pQuestionRecord);
            }else{
              int ii = ipQuestionRecordService.deletePQuestionRecordByQAC(pQuestionRecord);
              ipQuestionRecordService.insertPQuestionRecord(pQuestionRecord);
            }
        }

        return AjaxResult.success("操作成功");
    }

    @GetMapping("/selectExamByUser")
    public TableDataInfo selectExamByUser(Integer questionEquipmentId){
        PExam pExam = new PExam();

        pExam.setUserId(getUserId().intValue());
        pExam.setType(new Long(1));
        pExam.setType1(new Long(2));
        pExam.setPassword(getDeptId().toString());

        startPage();
        List<PExam> pExams = ipExamService.selectPExamByUserList(pExam);
        return  getDataTable(pExams);
    }


    /**
     * 查询错题
     *
     */
    @GetMapping("/findWrongQuestion")
    public TableDataInfo findWrongQuestion(Long questionEquipmentId) {
        PWrongQuestion pWrongQuestion = new PWrongQuestion();
        ArrayList<Object> objects = new ArrayList<>();
        pWrongQuestion.setLevel(questionEquipmentId);
        pWrongQuestion.setStatus(new Long(2));
        pWrongQuestion.setCreateBy(getUserId().toString());

        startPage();

        List<WrongQuestionResult> wrongQuestionResults = ipWrongQuestionService.selectwrongQuestion(pWrongQuestion);
        wrongQuestionResults.forEach(wrongQuestin ->{
            WrongQuestionResult wrongQuestionResult = new WrongQuestionResult();
            String[] allOption = wrongQuestin.getAllOption().split(",");
            WrongQuestionResult.Answer[] answer = new WrongQuestionResult.Answer[allOption.length];

            for (int i = 0; i < allOption.length; i++) {
                WrongQuestionResult.Answer answer1 = new WrongQuestionResult.Answer();
                answer1.setAnswer(allOption[i]);
                if(wrongQuestin.getQuType() == 2){
                    String[] split = wrongQuestin.getTrueOption().split(",");
                    for (int j = 0; j < split.length; j++) {
                        if (i == Integer.parseInt(split[j])) {
                            answer1.setIsTrue("true");
                            answer1.setAnalysis(wrongQuestin.getAnswerAnalysis());
                        }
                        answer[i] = answer1;
                    }
                }else{
                    if (i == Integer.parseInt(wrongQuestin.getTrueOption())) {
                        answer1.setIsTrue("true");
                        answer1.setAnalysis(wrongQuestin.getAnswerAnalysis());
                    }
                    answer[i] = answer1;
                }
            }
            wrongQuestin.setAnswerList(answer);
            objects.add(wrongQuestin);
        });
      return  getDataTable(wrongQuestionResults);
    }

    @GetMapping("/findWrongType")
    public AjaxResult findWrongType(Long questionEquipmentId) {
      PWrongQuestion pWrongQuestion = new PWrongQuestion();
      ArrayList<Object> objects = new ArrayList<>();
      pWrongQuestion.setLevel(questionEquipmentId);
      pWrongQuestion.setStatus(new Long(2));
      pWrongQuestion.setCreateBy(getUserId().toString());

      List<WrongQuestionResult> wrongQuestionResults = ipWrongQuestionService.selectwrongQuestion(pWrongQuestion);

      //按照题目类型分类出来
      Map<Integer, List<WrongQuestionResult>> collect = wrongQuestionResults
        .stream()
        .collect(Collectors.groupingBy(WrongQuestionResult::getQuType));

      //查询所有题目类型
      List<PQuestionTypeEntity> pQuestionTypeEntities = pQuestionTypeService.selectAll();

      HashMap<Integer, PQuestionTypeEntity> map = new HashMap<>();

      collect.forEach((quType,WQR)->{
        PQuestionTypeEntity pQuestionTypeEntity = pQuestionTypeEntities
          .stream()
          .filter(pQuestionType -> quType.equals(pQuestionType.getId()))
          .findFirst()
          .orElse(null);

        if(ObjectUtil.isNotNull(pQuestionTypeEntity)){
          map.put(
            WQR.size(),pQuestionTypeEntity
          );
        }
      });

      return  AjaxResult.success(map);
    }

    @GetMapping("/findWrongOneType")
    public TableDataInfo findWrongOneType(@RequestParam("questionEquipmentId")Long questionEquipmentId,@RequestParam("quType")Integer quTypeId) {
      PWrongQuestion pWrongQuestion = new PWrongQuestion();
      ArrayList<Object> objects = new ArrayList<>();
      pWrongQuestion.setLevel(questionEquipmentId);
      pWrongQuestion.setStatus(new Long(2));
      pWrongQuestion.setCreateBy(getUserId().toString());
      pWrongQuestion.setQuType(quTypeId);

      startPage();
      List<WrongQuestionResult> wrongQuestionResults = ipWrongQuestionService.selectwrongQuestionByType(pWrongQuestion);

      wrongQuestionResults.forEach(wrongQuestin ->{
        WrongQuestionResult wrongQuestionResult = new WrongQuestionResult();
        String[] allOption = wrongQuestin.getAllOption().split(",");
        WrongQuestionResult.Answer[] answer = new WrongQuestionResult.Answer[allOption.length];

        for (int i = 0; i < allOption.length; i++) {
          WrongQuestionResult.Answer answer1 = new WrongQuestionResult.Answer();
          answer1.setAnswer(allOption[i]);
          if(wrongQuestin.getQuType() == 2){
            String[] split = wrongQuestin.getTrueOption().split(",");
            for (int j = 0; j < split.length; j++) {
              if (i == Integer.parseInt(split[j])) {
                answer1.setIsTrue("true");
                answer1.setAnalysis(wrongQuestin.getAnswerAnalysis());
              }
              answer[i] = answer1;
            }
          }else{
            if (i == Integer.parseInt(wrongQuestin.getTrueOption())) {
              answer1.setIsTrue("true");
              answer1.setAnalysis(wrongQuestin.getAnswerAnalysis());
            }
            answer[i] = answer1;
          }
        }
        wrongQuestin.setAnswerList(answer);
        objects.add(wrongQuestin);
      });
      //。
      return  getDataTable(wrongQuestionResults);
    }

    /**
     * 这个接口和下面的接口所返回的都只是考试的信息的问题的信息，不会包括答案的信息，是学生端考试页面所要用到的接口
     * @param examId 考试id
     * @return
     */
    @GetMapping("/getExamInfoById")
    public AjaxResult getExamInfoById(@RequestParam Long examId) {
        PExam pExam = ipExamService.selectPExamById(examId);
        ArrayList<HashMap<String, Object>> list = ipExamService.examInfo(examId);
        AjaxResult ajaxResult =  AjaxResult.success();
        ajaxResult.put("examinationTime",pExam.getDuration());
        ajaxResult.put("data",list);
        return ajaxResult;
    }

    /**
     * 获取考试记录的接口(查阅)
     * @param examId 考试id
     * @return
     */
    @GetMapping("/getExamByUser")
    public AjaxResult getExamByUser(@RequestParam Long examId) {
        PExamRecordLog pExamRecordLog = new PExamRecordLog();
        pExamRecordLog.setExamId(examId);
        pExamRecordLog.setUserId(getUserId());
        ExamByLogResult pExamRecordLog1 = ipExamRecordLogService.selectPExamRecordLogByOne(pExamRecordLog);
        ExamByLogResult exam = ipExamService.examLogInfo(pExamRecordLog1);
        if(Objects.isNull(exam))
          return AjaxResult.error("无相关记录");
        return AjaxResult.success(pExamRecordLog1);
    }


    @GetMapping("/videoList")
    public TableDataInfo list(PVideo pVideo)
    {
        startPage();
        List<PVideo> list = pVideoService.selectPVideoList(pVideo);
        return getDataTable(list);
    }


    @GetMapping(value = "/getVideoInfo")
    public AjaxResult getVideoInfo(@RequestParam Long id)
    {
        return AjaxResult.success(pVideoService.selectPVideoById(id));
    }


}

